const JwtStrategy = require('passport-jwt').Strategy
const ExtractJwt = require('passport-jwt').ExtractJwt
const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken() // 从请求头获取token
// 引入Key
const ConfigManager = require('../lib/config.js')
opts.secretOrKey = ConfigManager.getSecretKey()

const mongoose = require('mongoose')
const User = mongoose.model('users')

module.exports = passport => {
  passport.use(new JwtStrategy(opts, async function (jwtPayload, done) {
    if (jwtPayload.exp - Math.floor(Date.now() / 1000) <= 3600) {
      const user = await User.findById(jwtPayload.id)
      if (user) {
        return done(null, user)
      }
      return done(null, false)
    }
  }))
}
